<!-- 寄存器 -->
<template>
  <div>
    <div v-if="this.$route.query.equipment_id  != undefined" class="main_operation">
      <div class="operation_left">
        <a-button v-if="routerShow($route,'register_add')" class="mr10" type="primary" @click="addBtn">添加</a-button>
        <a-button v-if="routerShow($route,'template_add')" class="mr10" type="primary" @click="setTemplate">保存模板</a-button>
        <a-button v-if="routerShow($route,'template_callTemplate')" class="mr10" type="primary" @click="getTemplate">调用模板</a-button>
      </div>
      <div class="operation_right">
        <h3>当前设备名称：{{equipmentDetailData.name}}</h3>
      </div>
    </div>
    <a-table
      bordered
      size="middle"
      :pagination="false"
      :loading="tableLoad"
      :columns="Fields"
      :dataSource="dataLists.data"
      :scroll="{ x: 1890, y:500}"
    >
      <!-- :rowKey="record => record.row_num" -->
      <!-- :scroll="{x: 1500, y: 500 }" -->
      <template slot="row_num" slot-scope="text, record">
        <template v-if="record.ifShow">
          <span style="color: red;">新添</span>
        </template>
        <template v-else>
          <span v-if="text == '新添'" style="color: red;">{{text}}</span>
          <span v-else>{{text}}</span>
        </template>
      </template>
      <template slot="name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-input v-model="record.name" />
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="unit_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.unit_name" placeholder="请选择单位">
            <a-select-option value="">无</a-select-option>
            <a-select-option value="℃">℃</a-select-option>
            <a-select-option value="%">%</a-select-option>
            <a-select-option value="V">V</a-select-option>
            <a-select-option value="A">A</a-select-option>
          </a-select>
        </template>
        <template v-else>{{record.unit_name == ''? '无' : record.unit_name }}</template>
      </template>
      <template slot="decimal_point" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.decimal_point" placeholder="请选择小数点位">
            <a-select-option value="0">0</a-select-option>
            <a-select-option value="1">1</a-select-option>
            <a-select-option value="2">2</a-select-option>
            <a-select-option value="3">3</a-select-option>
            <a-select-option value="4">4</a-select-option>
            <a-select-option value="5">5</a-select-option>
            <a-select-option value="6">6</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="type_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.type_name" placeholder="请选择数据类型">
            <a-select-option value="整型">整型</a-select-option>
            <a-select-option value="开关量">开关量</a-select-option>
            <a-select-option value="浮点型">浮点型</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="plc_type_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.plc_type_name" placeholder="请选择寄存器类型">
            <a-select-option value="S(0-1023)">S(0-1023)</a-select-option>
            <a-select-option value="X(0~377)">X(0~377)</a-select-option>
            <a-select-option value="Y(0-377)">Y(000-377)</a-select-option>
            <a-select-option value="T(0-255)">T(0-255)</a-select-option>
            <a-select-option value="M(0-4095)">M(0-4095)</a-select-option>
            <a-select-option value="C(0-255)">C(0-255)</a-select-option>
            <a-select-option value="D(0-11999)">D(0-11999)</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="address" slot-scope="text, record">
        <template v-if="record.editable">
          <a-input v-model="record.address" />         
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="read_write_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.read_write_name" placeholder="请选择读写">
            <a-select-option value="只读">只读</a-select-option>
            <a-select-option value="读写">读写</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="data_bits_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.data_bits_name" placeholder="请选择数据长度">
            <a-select-option value="1位">1位</a-select-option>
            <a-select-option value="2位">2位</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="number_type_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.number_type_name" placeholder="请选择数值类型">
            <a-select-option value="无符号整型">无符号整型</a-select-option>
            <a-select-option value="有符号整型">有符号整型</a-select-option>
            <!-- <a-select-option value="4字节无符号整型">4字节无符号整型</a-select-option>
            <a-select-option value="4字节有符号整型">4字节有符号整型</a-select-option>
            <a-select-option value="4字节浮点数">4字节浮点数</a-select-option> -->
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="byte_order_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.byte_order_name" placeholder="请选择字节顺序">
            <a-select-option value="ABCD">AB CD</a-select-option>
            <a-select-option value="CDAB">CD AB</a-select-option>
            <a-select-option value="BADC">BA DC</a-select-option>
            <a-select-option value="DCBA">DC BA</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="unitID" slot-scope="text, record">
        <template v-if="record.editable">
          <a-input v-model="record.unitID" placeholder="请输入数据格式" />
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="data_type_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.data_type_name" placeholder="请选择数值分类">
            <a-select-option value="普通">普通</a-select-option>
            <a-select-option value="车数">车数</a-select-option>
            <a-select-option value="能量">能量</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="format" slot-scope="text, record">
        <template v-if="record.editable">
          <a-input v-model="record.format" placeholder="请输入命令描述" />
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="pay_status_name" slot-scope="text, record">
        <template v-if="record.editable">
          <a-select v-model="record.pay_status_name" placeholder="是否收费">
            <a-select-option value="免费">免费</a-select-option>
            <a-select-option value="付费">付费</a-select-option>
            <a-select-option value="平台">平台</a-select-option>
          </a-select>
        </template>
        <template v-else>{{text}}</template>
      </template>
      <template slot="action" slot-scope="text, record ,index">
        <!-- <div class='editable-row-operations'> -->
          <span v-if="record.editable">
            <a-button size="small" class="mr5 mb5" type="primary" @click="save(record, index)">保存</a-button>
            <a-popconfirm v-if="!record.ifShow" title='确定不保存吗?' @confirm="() => cancel(record.key)">
              <a-button  size="small" class="mr5" type="danger">取消</a-button>
            </a-popconfirm>
            <a-button v-else size="small" class="mr5" @click="() => addCancel(record, index)" type="danger">取消</a-button>
          </span>
          <span v-else>
            <a-button v-if="routerShow($route,'register_update')" size="small" class="mr5 mb5" type="primary" @click="() => edit(record.key)">编辑</a-button>
            <a-button v-if="routerShow($route,'register_delete')" size="small" class="mr5" type="danger" @click="delBtn(record, index)">删除</a-button>
          </span>
      </template>
    </a-table>
    <div class="pageBox">
      <a-pagination
        v-if="this.$route.query.equipment_id  != undefined"
        :total="dataLists.total"
        :showTotal="total => `共 ${total} 条数据`"
        :pageSize="dataLists.per_page"
        :defaultCurrent="1"
        @change="pageChange"
      />
    </div>
    <a-list :split="false" size="small" :dataSource="textWord">
      <a-list-item slot="renderItem" slot-scope="item">{{item}}</a-list-item>
      <div slot="header">说明：</div>
    </a-list>
    <a-modal
      :title="templateTitle"
      :visible="templateModel"
      @ok="templateOk"
      @cancel="templateModel = false"
      :confirmLoading="templateLoading"
    >
      <a-form>
        <a-form-item required label="模板名称:" :label-col="{ md: 5 ,xs: 24 }" :wrapper-col="{ md: 19 ,xs: 24 }">
          
          <a-input v-if="templateTitle == '保存模板'" v-model="templateFrom.tpl_name" placeholder="请输入模板名称" />
          <a-select v-else allowClear v-model="templateFrom.tpl_id">
            <a-select-option v-for="item in TemplateAllData" :value="item.id" :key="item.id">{{item.tpl_name}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { showErrors, showError, showSuccess } from '@/utils/showMsg';
const textWord = [
  "1. 所有数值输入为 10 进制，如寄存器地址、最小原始值、最大原始值。",
  "2. 数值映射：最小原始值 ~ 最大原始值 -> 最小值 ~ 最大值，如温度：-400 ~ 800 -> -40 ~ 80，最小值、最大值分别与最小原始值、最大原始值相等时不作映射。",
  "3. 小数位、最小值、最大值、最小原始值、最大原始值、数据格式字段，对开关量或 16 位布尔型数据不需填写，对数值型数据必需填写。",
  "4. 数据位字段，只在数据格式为 16 位布尔时需要填写。",
  "5. 字节顺序字段，只在数据格式为 32 位时需要填写。",
  "6. UnitID 字段，仅对 Modbus TCP 设备有效。"
];
export default {
  name: "register",
  data() {
    return {
      cacheData: [],
      textWord,
      /* 通用模块 */
      //列表
      tableLoad: false, //列表loading状态
      formList: {
        //列表信息
        page: 1
      },
      selectedRowKeys: [], //勾选的id
      /* 通用模块end */

      /* 添加编辑 */
      titleModel: "", //标题
      visible: false, //窗口显示隐藏
      confirmLoading: false, //按钮loading状态
      formItem: {},
      /* 添加编辑end */

      /* 模板 */
      templateTitle: '',
      templateLoading: false,
      templateModel: false,
      templateFrom:{
        tpl_name: '',
        equipment_id: '',
      }
      /* 模板end */
    };
  },
  mounted() {
    this.equipmentAll();
    const id = this.$route.query.equipment_id;
    this.formList.equipment_id = id;
    if(id != undefined && id != NaN){
      this.equipmentDetail(id)
      this.changeData();
    }
  },
  computed: {
    ...mapState({
      Fields: state => state.equiRegister.Fields,
      dataLists: state => state.equiRegister.dataLists,
      requestCode: state => state.equiRegister.requestCode,
      equipmentData: state => state.equipment.equipmentData, //设备名称信息
      equipmentDetailData: state => state.equipment.itemDetail, //设备详情信息
      addItemData: state => state.equiRegister.addItemData,
      TemplateAllData: state => state.equiRegister.TemplateAllData,
    })
    // .map(item => ({ ...item }))
  },
  watch: {
    dataLists(){
      this.cacheData = this.dataLists.data.map(item => ({ ...item }))
    },
  },
  methods: {
    /* 模板 */
    setTemplate(){
      this.templateTitle = '保存模板'
      let isedit = false
      this.dataLists.data.some(item=>{
        if(item.editable){
          isedit = item.editable
          return item.editable
        }
      })
      if(isedit){
        this.$error({
          title: `当前有寄存器处于编辑状态，无法保存模板`,
          content: (
            <p style="color: red;">检测到当前寄存器列表有寄存器处于编辑状态，为确保数据完整性，请先保存编辑状态的寄存器！</p>
          ),
        });
      } else {
        this.templateFrom = {
          tpl_name: '',
          equipment_id: '',
        }
        this.templateModel = true
        const id = this.$route.query.equipment_id;
        this.templateFrom.equipment_id = id
        console.log(this.templateFrom);
      }
    },
    getTemplate(){
      this.templateTitle = '调用模板'
      let isedit = false
      this.dataLists.data.some(item=>{
        if(item.editable){
          isedit = item.editable
          return item.editable
        }
      })
      if(isedit){
        this.$error({
          title: `当前有寄存器处于编辑状态，无法调用模板`,
          content: (
            <p style="color: red;">检测到当前寄存器列表有寄存器处于编辑状态，为确保数据完整性，请先保存编辑状态的寄存器！</p>
          ),
        });
      } else {
        this.templateFrom = {
          tpl_id: '',
          equipment_id: '',
        }
        this.templateAll()
        this.templateModel = true
        const id = this.$route.query.equipment_id;
        this.templateFrom.equipment_id = id
        console.log(this.templateFrom);
      }
    },
    templateOk(){
      if (this.templateFrom.tpl_name == '') {
        showError('模板名称不能为空')
        return null
      }
      const that = this
      this.templateLoading = true
      if(this.templateTitle == '保存模板'){
        this.templateAdd(this.templateFrom).then(response => {
          that.templateLoading = false
          console.log(response);
          if (response.data.errorCode === 0) {
            that.templateModel = false
            showSuccess(response.data.result)
          } else if(response.status === 422) {
            showErrors( response.data.errors )
          } else {
            showError( response.data.message )
          }
        })
      } else if(this.templateTitle == '调用模板') {
        this.callTemplate(this.templateFrom).then(response => {
          that.templateLoading = false
          console.log(response);
          if (response.data.errorCode === 0) {
            that.templateModel = false
            showSuccess(response.data.result)
            this.changeData();
          } else if(response.status === 422) {
            showErrors( response.data.errors )
          } else {
            showError( response.data.message )
          }
        })
      }
    },
    /* 模板end */
    addCancel(item, index){
      // console.log(item,index);
      this.dataLists.total--
      this.dataLists.data.splice(index,1)

    },
    handleChange (value, key, column) {
      const newData = [...this.dataLists.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.dataLists.data = newData
      }
    },
    edit (key) {
      const newData = [...this.dataLists.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target.editable = true
        this.dataLists.data = newData
      }
    },
    // 保存
    save (row, index) {
      this.formItem = {}
      console.log(row);
      const newData = [...this.dataLists.data]
      const target = newData.filter(item => row.key === item.key)[0]
      if(row.ifShow) {
        //接口添加
        let additem = {
          equipment_id: row.equipment_id,
          name: row.name,
          address: row.address,
          unitID: row.unitID,
          format: row.format,
          unit: this.isUnit(row.unit_name),
          decimal_point: row.decimal_point,
          type: this.isType(row.type_name),
          plc_type: this.isPlcType(row.plc_type_name),
          read_write: this.isReadWrite(row.read_write_name),
          data_bits: this.isDataBits(row.data_bits_name),
          byte_order: this.isByteOrder(row.byte_order_name),
          number_type: this.isNumberType(row.number_type_name),
          pay_status: this.isPayStatus(row.pay_status_name),
          data_type: this.isDataType(row.data_type_name),
        };
        this.dataAdd(additem);
        setTimeout(() => {
          console.log(this.requestCode);
          if (this.requestCode == 0) {
            this.addItemData.row_num = index+1
            this.addItemData.key = this.addItemData.row_num
            this.dataLists.data.splice(index,1,this.addItemData)
          }
        }, 1000);
      } else {
        this.formItem = {
          id: row.id,
          equipment_id: row.equipment_id,
          name: row.name,
          address: row.address,
          unitID: row.unitID,
          format: row.format,
          unit: this.isUnit(row.unit_name),
          decimal_point: row.decimal_point,
          type: this.isType(row.type_name),
          plc_type: this.isPlcType(row.plc_type_name),
          read_write: this.isReadWrite(row.read_write_name),
          data_bits: this.isDataBits(row.data_bits_name),
          byte_order: this.isByteOrder(row.byte_order_name),
          number_type: this.isNumberType(row.number_type_name),
          pay_status: this.isPayStatus(row.pay_status_name),
          data_type: this.isDataType(row.data_type_name)
        };
        this.dataEdit(this.formItem);
      }
      setTimeout(() => {
        if (this.requestCode === 0) {
          if (target) {
            delete target.editable
            this.dataLists.data = newData
            this.cacheData = newData.map(item => ({ ...item }))
          }
        }
      }, 1000);
    },
    cancel (key) {
      console.log(key);
      const newData = [...this.dataLists.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
        delete target.editable
       this.dataLists.data = newData
      }
    },
    ...mapActions({
      getLists: "equiRegister/getLists", //列表
      dataAdd: "equiRegister/dataAdd", //添加
      dataEdit: "equiRegister/dataEdit", //编辑
      dataDel: "equiRegister/dataDel", //删除
      registerAll: "equiRegister/registerAll", //设备寄存器详细信息
      equipmentAll: "equipment/equipmentAll", //设备名称信息
      equipmentDetail: 'equipment/dataDetail', //设备基础信息详情
      templateAdd: "equiRegister/templateAdd", //模板添加
      callTemplate: "equiRegister/callTemplate", //模板调用
      templateAll: "equiRegister/templateAll", //模板all信息
      
    }),
    /* 通用模块 */
    // 勾选
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    // 重新获取列表数据
    changeData() {
      this.tableLoad = true;
      setTimeout(() => {
        this.getLists(this.formList);
        this.tableLoad = false;
      }, 800);
    },
    //搜索
    onSearch(val) {
      this.formList = {
        //列表信息
        equipment_id: val,
        page: 1
      };
      this.changeData();
    },
    // 页码
    pageChange(page) {
      this.formList.page = page;
      this.getLists(this.formList);
    },
    /* 通用模块end */

    /* 添加编辑 */
    // 添加
    addBtn() {
      const equipment_id = this.$route.query.equipment_id;
      const { dataLists } = this
      this.dataLists.total = dataLists.total + 1
      let rowItem = {
        key: dataLists.total,
        ifShow: true,
        row_num: dataLists.total,
        editable: true,
        equipment_id: Number(equipment_id),
        name: '',
        address: '',
        unitID: '',
        format: '',
        unit_name: '',
        decimal_point:'',
        type_name:'',
        plc_type_name: '',
        read_write_name: '',
        data_bits_name: '',
        byte_order_name: '',
        number_type_name:'',
        pay_status_name: '免费',
        data_type_name: '普通',
      };
      this.dataLists.data = [...this.dataLists.data, rowItem]
      // console.log('data数量', this.dataLists.total);
      // console.log('data数据', this.dataLists);
    },
    /* 转换 */
    isPayStatus(val){
      if(val == '免费'){
        return 0
      } else if(val == '付费'){
        return 1
      } else if(val == '平台'){
        return 2
      }else {
        return ''
      }
    },
    isDataBits(val){
      if (val == "1位") {
        return 1
      } else if(val == "2位"){
        return 2
      } else {
        return ''
      }
    },
    isReadWrite(val){
      switch (val) {
        case "只读":
          return 1;
        case "读写":
          return 2;
        default:
          return ''; 
      }
    },
    isUnit(val)  {
        switch (val) {
        case "℃":
          return 1;
        case "%":
          return 2;
        case "V":
          return 3;
        case "A":
          return 4;
        default:
          return ''; 
      }
    },
    isNumberType(val) {
      switch (val) {
        case "无符号整型":
          return 1;
        case "有符号整型":
          return 2;
        default:
          return '';
      }
    },
    isPlcType(val) {
      switch (val) {
        case "S(0-1023)":
          return 1;
        case "X(0~377)":
          return 2;
        case "Y(0-377)":
          return 3;
        case "T(0-255)":
          return 4;
        case "M(0-4095)":
          return 5;
        case "C(0-255)":
          return 6;
        case "D(0-11999)":
          return 7;
        default:
          return '';
      }
    },
    isType(val) {
      switch (val) {
        case "整型":
          return 1;
        case "开关量":
          return 2;
        case "浮点型":
          return 3;
        default:
          return '';
      }
    },
    isByteOrder(val) {
      switch (val) {
        case "ABCD":
          return 1;
        case "CDAB":
          return 2;
        case "BADC":
          return 3;
        case "DCBA":
          return 4;
        default:
          return '';
      }
    },
    isDataType(val) {
      switch (val) {
        case "普通":
          return 0;
        case "车数":
          return 1;
        case "能量":
          return 2;
        default:
          return '';
      }
    },
    /* 转换end */
    /* 添加编辑end */

    /* 删除 */
    delBtn(item, index) {
      let _this = this;
      this.$confirm({
        title: `您确定要删除该寄存器吗?`,
        content: `删除后将不可恢复,请仔细核对!`,
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          _this.dataDel(item.id);
          _this.dataLists.data.splice(index,1)
          _this.dataLists.total--
          // _this.changeData();
        }
      });
    }
  }
};
</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
